package com.example.webmagic;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import us.codecraft.webmagic.Spider;

import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Created by Geekkiller on 2017/11/16.
 */
public class JDBCDao {

    private static Connection getConn() {
        Connection connection = null;
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/data_repository?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";
        try {
            Class.forName(driver); // classLoader,加载对应驱动
            connection = (Connection) DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static int insert(BaozouNews news) {
        Connection conn = getConn();
        int i = 0;
        String sql = "insert into baozou(author,time,content) VALUES (?,?,?);";
        PreparedStatement pstmt;
        try {
            pstmt = (PreparedStatement) conn.prepareStatement(sql);
            pstmt.setString(1, news.getAuthor());
            pstmt.setString(2, news.getTime());
            pstmt.setString(3, news.getContent());
            i = pstmt.executeUpdate();
            pstmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }

    public static void main(String[] args) {
        Spider.create(new BaoZouProcessor()).addUrl("http://baozoumanhua.com/text")
                .addPipeline(new BaoZouPipeLine())
                .thread(5)
                .run();
    }

}
